﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using OpalisConsole.EndUserService;
namespace OpalisConsole.Views.Administration
{
    public partial class UserImpersonation : Page
    {
        public UserImpersonation()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!((bool)App.Current.Resources["FreshStartAdmin"] || (bool)App.Current.Resources["FreshStartApprover"]))
            {
                this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
            }
            else
            {
                try
                {
                    boxMachine.Text = Application.Current.Resources["ComputerName"].ToString();
                }
                catch { }
                try
                {
                    boxUserName.Text = Application.Current.Resources["FullUserID"].ToString();
                }
                catch { }
                
            }
        }

        private void btnChangeCurrentUser_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorUserManagement.IsBusy = true;
            busyIndicatorUserManagement.BusyContent = "Changing User";
            string UserMachine = boxMachine.Text;
            string UserName = boxUserName.Text;
            
            string UserID = UserName.Split('\\')[1];
            string UserDomain = UserName.Split('\\')[0];

            if (Application.Current.Resources.Contains("ScheduledDate")) { Application.Current.Resources.Remove("ScheduledDate"); }
            Application.Current.Resources.Add("ScheduledDate", DateTime.Now.AddHours(1).Subtract(new TimeSpan(0, DateTime.Now.Minute, 0)));

            if (Application.Current.Resources.Contains("UserID")) { Application.Current.Resources.Remove("UserID"); }
            Application.Current.Resources.Add("UserID", UserID);

            if (Application.Current.Resources.Contains("FullUserID")) { Application.Current.Resources.Remove("FullUserID"); }
            Application.Current.Resources.Add("FullUserID", UserName);

            if (Application.Current.Resources.Contains("Computer_ID")) { Application.Current.Resources.Remove("Computer_ID"); }
            Application.Current.Resources.Add("Computer_ID", "Not Approved");

            if (Application.Current.Resources.Contains("UserDomain")) { Application.Current.Resources.Remove("UserDomain"); }
            Application.Current.Resources.Add("UserDomain", UserDomain);

            if (Application.Current.Resources.Contains("ComputerName")) { Application.Current.Resources.Remove("ComputerName"); }
            Application.Current.Resources.Add("ComputerName", UserMachine);

            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.getComputerOwnerWithUsernameCompleted += new EventHandler<getComputerOwnerWithUsernameCompletedEventArgs>(proxy_getComputerOwnerCompleted);
            proxy.getComputerOwnerWithUsernameAsync(UserMachine, UserID);
            
        }

        void proxy_getComputerOwnerCompleted(object sender, getComputerOwnerWithUsernameCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (Application.Current.Resources.Contains("Status")) { Application.Current.Resources.Remove("Status"); }
                Application.Current.Resources.Add("Status", "Not Owner");
                busyIndicatorUserManagement.IsBusy = false;
            }
            else
            {
                string ownerName = e.Result.ToString();
                string requester = Application.Current.Resources["FullUserID"].ToString().ToUpper();
                //owner
                if (requester.Contains(ownerName.ToUpper()) && !ownerName.Equals(String.Empty))
                {
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.getApprovedComputerIDCompleted += new EventHandler<getApprovedComputerIDCompletedEventArgs>(proxy_getApprovedComputerIDCompleted);
                    proxy.getApprovedComputerIDAsync(Application.Current.Resources["ComputerName"].ToString());
                }
                //not Owner
                else
                {
                    if (Application.Current.Resources.Contains("Status")) { Application.Current.Resources.Remove("Status"); }
                    Application.Current.Resources.Add("Status", "Not Owner");
                    busyIndicatorUserManagement.IsBusy = false;
                }
            }
        }
        void proxy_getApprovedComputerIDCompleted(object sender, getApprovedComputerIDCompletedEventArgs e)
        {
            
            String computerID = e.Result.ToString();
            if (Application.Current.Resources.Contains("Computer_ID"))
            {
                Application.Current.Resources.Remove("Computer_ID");
            }

            Application.Current.Resources.Add("Computer_ID", computerID);

            if (computerID.Equals("Not Approved"))
            {
                if (Application.Current.Resources.Contains("Status")) { Application.Current.Resources.Remove("Status"); }
                Application.Current.Resources.Add("Status", "Not Approved");
                busyIndicatorUserManagement.IsBusy = false;
            }
            else
            {
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getRequestStatusCompleted += new EventHandler<getRequestStatusCompletedEventArgs>(proxy_getRequestStatusCompleted);
                proxy.getRequestStatusAsync(Application.Current.Resources["ComputerName"].ToString());
            }
        }
        void proxy_getRequestStatusCompleted(object sender, getRequestStatusCompletedEventArgs e)
        {
            String result = e.Result.ToString();
            if (result.Equals("Not Scheduled"))
            {
                if (Application.Current.Resources.Contains("Status")) { Application.Current.Resources.Remove("Status"); }
                Application.Current.Resources.Add("Status", "Not Scheduled");                
            }
            else
            {
                String Imaging_ID = result.Split(',')[0];
                String OSDComputerName = result.Split(',')[1];
                String Status = result.Split(',')[2];
                DateTime StartDateTime = Convert.ToDateTime(result.Split(',')[3]).ToLocalTime();
                String userDataYN = result.Split(',')[4];

                if (Status.Equals("Scheduling") || Status.Equals("New")) { Application.Current.Resources.Add("Status", "Scheduled"); }
                else
                {
                    if (Application.Current.Resources.Contains("Status")) { Application.Current.Resources.Remove("Status"); }
                    Application.Current.Resources.Add("Status", Status); 
                }

                if (Application.Current.Resources.Contains("ScheduledDate")) { Application.Current.Resources.Remove("ScheduledDate"); }
                Application.Current.Resources.Add("ScheduledDate", StartDateTime);

                if (Application.Current.Resources.Contains("Imaging_ID")) { Application.Current.Resources.Remove("Imaging_ID"); }
                Application.Current.Resources.Add("Imaging_ID", Imaging_ID);

                if (Application.Current.Resources.Contains("Data Choice")) { Application.Current.Resources.Remove("Data Choice"); }
                Application.Current.Resources.Add("Data Choice", userDataYN);
            }

            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.getEntriesPerDayCompleted += new EventHandler<getEntriesPerDayCompletedEventArgs>(proxy_getEntriesPerDayCompleted);

            TimeSpan span = DateTime.UtcNow.Subtract(DateTime.Now);
            String minutes = Math.Round(span.TotalMinutes).ToString();
            proxy.getEntriesPerDayAsync(minutes);
        }
        void proxy_getEntriesPerDayCompleted(object sender, getEntriesPerDayCompletedEventArgs e)
        {
            if (e.Result.Count > 0)
            {
                List<EntriesPerDate> dayList = new List<EntriesPerDate>();
                foreach (EntriesPerDate entry in e.Result)
                {
                    if (entry.NumberOfScheduled > (int)Application.Current.Resources["MAX_ENTRIES_PER_HOUR"] * 24)
                    {
                        dayList.Add(entry);
                    }
                }
                if (dayList.Count != 0)
                {
                    if (Application.Current.Resources.Contains("DAY_LIST")) { Application.Current.Resources.Remove("DAY_LIST"); }
                    Application.Current.Resources.Add("DAY_LIST", dayList);
                }
                else
                {
                    dayList.Add(new EntriesPerDate() { Day = DateTime.Now.AddDays(-1), NumberOfScheduled = 0 });
                    if (Application.Current.Resources.Contains("DAY_LIST")) { Application.Current.Resources.Remove("DAY_LIST"); }
                    Application.Current.Resources.Add("DAY_LIST", dayList);
                }
                
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembershipCompleted_Developer);
                proxy.checkGroupMembershipAsync(Application.Current.Resources["UserID"].ToString(), "GMI_APP_MSDN_Microsoft_SI", Application.Current.Resources["UserDomain"].ToString());
            }
        }
        
        void proxy_checkGroupMembershipCompleted_Developer(object sender, checkGroupMembershipCompletedEventArgs e)
        {
            if ((bool)e.Result) 
            {
                if (Application.Current.Resources.Contains("DeveloperStatus")) { Application.Current.Resources.Remove("DeveloperStatus"); }
                Application.Current.Resources.Add("DeveloperStatus", true); 
            }
            else 
            {
                if (Application.Current.Resources.Contains("DeveloperStatus")) { Application.Current.Resources.Remove("DeveloperStatus"); }
                Application.Current.Resources.Add("DeveloperStatus", false); 
            }
            busyIndicatorUserManagement.IsBusy = false;
        }
    }
}
